package main

import (
	"C"
	"bytes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"

	"gitee.com/t115liyanpeng/license/sm3"
	sm4 "gitee.com/t115liyanpeng/license/sm4"
)

func main() {

	//sm3 sm4 加解密示例
	hash := sm3.New()

	hash.Write([]byte("1657175902077"))

	result := hash.Sum(nil)

	println("sm3 hash = ", hex.EncodeToString(result))

	a := []byte("erl1233312")
	key := []byte("aabbccddaabbccdd")
	decrypto := SM4Encrypt(a, key)
	fmt.Println("sm4加密后：", hex.EncodeToString(decrypto))
	i := SM4Decrypto(decrypto, key)
	fmt.Println("sm4解密后：", string(i))
}

//export SM4Encrypt
func SM4Encrypt(src []byte, key []byte) []byte {

	block, e := sm4.NewCipher(key)
	if e != nil {
		fmt.Println("newCrypther faild !")
	}
	a := block.BlockSize() - len(src)%block.BlockSize()
	repeat := bytes.Repeat([]byte{byte(a)}, a)
	newsrc := append(src, repeat...)

	dst := make([]byte, len(newsrc))
	blockMode := cipher.NewCBCEncrypter(block, key[:block.BlockSize()])
	blockMode.CryptBlocks(dst, newsrc)
	return dst

}

//export SM4Decrypto
func SM4Decrypto(dst, key []byte) []byte {

	block, e := sm4.NewCipher(key)
	if e != nil {
		fmt.Println("newcipher faild! ")
	}
	blockMode := cipher.NewCBCDecrypter(block, key[:block.BlockSize()])

	src := make([]byte, len(dst))
	blockMode.CryptBlocks(src, dst)

	num := int(src[len(src)-1])
	newsrc := src[:len(src)-num]
	return newsrc
}

//export SM3HmacByStr
func SM3HmacByStr(src string) string {

	return SM3HmacBysBytes([]byte(src))
}

//export SM3HmacBysBytes
func SM3HmacBysBytes(bytes []byte) string {
	hash := sm3.New()
	hash.Write(bytes)
	result := hash.Sum(nil)
	return hex.EncodeToString(result)

}
